package com.ikingtech.platform.service.system.config.service.loader;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import com.ikingtech.framework.sdk.enums.integration.PlatformConfigTypeEnum;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.framework.sdk.wechat.mini.api.WechatMiniConfigLoader;
import com.ikingtech.framework.sdk.wechat.mini.model.WechatMiniDTO;
import com.ikingtech.platform.service.system.config.entity.ConfigDO;
import com.ikingtech.platform.service.system.config.service.repository.ConfigRepository;
import lombok.RequiredArgsConstructor;

import java.util.List;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public class WechatMiniConfigLoaderImpl implements WechatMiniConfigLoader {

    private final ConfigRepository repo;

    @Override
    public WechatMiniDTO load(String wechatMiniId) {
        String dataId = this.repo.getObj(Wrappers.<ConfigDO>lambdaQuery()
                .select(ConfigDO::getDataId)
                .eq(ConfigDO::getType, PlatformConfigTypeEnum.WECHAT_MINI_CONFIG.name())
                .eq(ConfigDO::getPropertyValue, wechatMiniId), String.class::cast);
        if (Tools.Str.isBlank(dataId)) {
            throw new FrameworkException("wechatMiniNotFound");
        }
        List<ConfigDO> configEntities = this.repo.list(Wrappers.<ConfigDO>lambdaQuery().eq(ConfigDO::getDataId, dataId));
        WechatMiniDTO wechatMini = new WechatMiniDTO();
        configEntities.forEach(configEntity -> {
            switch (configEntity.getPropertyKey()) {
                case "id":
                    wechatMini.setId(configEntity.getPropertyValue());
                    break;
                case "name":
                    wechatMini.setName(configEntity.getPropertyValue());
                    break;
                case "appId":
                    wechatMini.setAppId(configEntity.getPropertyValue());
                    break;
                case "appSecret":
                    wechatMini.setAppSecret(configEntity.getPropertyValue());
                    break;
                default:
                    break;
            }
        });
        return wechatMini;
    }
}
